
#include "mem_pool.h"

void * CMem_Pool::MemPoolCreate(size_t size)
{

	if (size==0 || size>=1024*512)  
			return NULL;  


		mempool *pool = (mempool*)calloc(1,sizeof(mempool));  
		pool->size = 1024*size;  
		pool->raw_area = calloc(1,1024*size);  
		pool->cursor = pool->raw_area;  

		return pool;  

}
size_t CMem_Pool::mempool_could_allocate(mempool* pool, size_t n)
{

	// cursor will out of the end  
    if (((char*)pool->cursor - (char*)pool->raw_area)+n > pool->size)  
        return 0;  
    else      
        return 1;  

}

void* CMem_Pool::mempool_allocate(mempool* pool, size_t n)
{
	 // no space here  
    if (NULL==pool || NULL==pool->raw_area || !mempool_could_allocate(pool,n))  
        return NULL;  
  
    void* ret = pool->cursor;  
    // move the cursor  
    pool->cursor = (void*)((char*)pool->cursor + n);  
  
    return ret;  	

}
size_t CMem_Pool::mempool_left(mempool *pool)
{

	 if (NULL == pool)  
        return -1;  
    else return pool->size - ((char*)pool->cursor - (char*)pool->raw_area);  

}
void CMem_Pool::mempool_destroy(mempool* pool)
{

	free(pool->raw_area);  
    pool->cursor = pool->raw_area = NULL;     
    pool->size = 0;  

}


